package org.aplikator.server.rpc.handler;

import java.util.ArrayList;
import java.util.List;

import org.aplikator.client.data.Record;
import org.aplikator.client.descriptor.ViewDTO;
import org.aplikator.client.rpc.impl.GetSuggestions;
import org.aplikator.client.rpc.impl.GetSuggestionsResponse;
import org.aplikator.client.widgets.ReferenceFieldWidget.ItemSuggestion;
import org.aplikator.server.Context;
import org.aplikator.server.persistence.Persister;
import org.aplikator.server.persistence.PersisterFactory;
import org.aplikator.server.rpc.CommandHandler;

import com.google.gwt.user.client.ui.SuggestOracle;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;

public class GetSuggestionsHandler implements CommandHandler<GetSuggestions, GetSuggestionsResponse> {

    private Persister persister = PersisterFactory.getPersister();

    public GetSuggestionsHandler() {

    }

    public GetSuggestionsResponse execute(GetSuggestions command, Context context) {
        ViewDTO view = command.getView();
        SuggestOracle.Request req = command.getRequest();
        view.setSearchString(req.getQuery());
        int offset = persister.getRecordCount(view, null, null, true, context);
        List<Record> records = persister.getPage(view, null, null, offset, req.getLimit() > 0 ? req.getLimit() : 15, context);
        SuggestOracle.Response resp = new SuggestOracle.Response();

        List<Suggestion> suggestions = new ArrayList<Suggestion>(req.getLimit());

        for (Record rec : records) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < view.getProperties().size(); i++) {
                sb.append(view.getProperties().get(i).getValue(rec));
                sb.append("; ");
            }
            int pk = rec.getPrimaryKey().getId();
            Object val = view.getSortProperty().getValue(rec);
            String repl = val!=null?val.toString():"";
            suggestions.add(new ItemSuggestion(sb.toString(), pk, repl, rec));
        }
        resp.setSuggestions(suggestions);
        return new GetSuggestionsResponse(resp);
    }

}
